/*
 *  Copyright (c) 2019-2020, 冷冷 (wangiegie@gmail.com).
 *  <p>
 *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 * https://www.gnu.org/licenses/lgpl.html
 *  <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alex.core.exception;

import com.ddcx.domain.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


/**
 * @author lengleng
 * @date 2019/2/1
 * 全局的的异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
	/**
	 * 全局异常.
	 *
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(Exception.class)
	public ApiResponse exception(Exception e) {
		log.error("全局异常信息 ex={}", e.getMessage(), e);
		e.printStackTrace();
		if(e instanceof CustomException){
			return new ApiResponse(e.getMessage());
		}else{
			return new ApiResponse(500, e.getMessage(),"网络异常,请稍后再试!");
		}
	}

	/**
	 * 请求参数绑定异常全局处理
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BindException.class)
	public ApiResponse exception(BindException e) {
		log.error("请求绑定参数异常 ex={}", e.getMessage(), e);
		List<FieldError> fieldErrors = e.getFieldErrors();
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("{");
		for (FieldError fe : fieldErrors) {
			stringBuffer.append(String.format("%s:%s,", fe.getField(), fe.getDefaultMessage()));
		}
		stringBuffer.deleteCharAt(stringBuffer.length()-1);
		stringBuffer.append("}");
		log.error(stringBuffer.toString());
		return new ApiResponse(400, stringBuffer.toString(), "参数不合格");
	}

	/**
	 * validation Exception
	 *
	 * @param exception
	 * @return R
	 */
	@ExceptionHandler({CustomException.class})
	public ApiResponse bodyValidExceptionHandler(CustomException exception) {
		return new ApiResponse(exception.getCode(),exception.getErrorMsg(),exception.getMsg());
	}

	/**
	 * 处理CustomRuntimeException异常
	 *
	 * @param exception
	 * @return
	 */
	@ExceptionHandler({CustomRuntimeException.class})
	public ApiResponse customRuntimeExceptionHandler(CustomRuntimeException exception) {
		return new ApiResponse(exception.getCode(), exception.getErrMsg(), exception.getErrMsg());
	}

}
